/*!
* shrimp7 JS v1.1.0
* Copyright 2009 Rens Sparrius
*
* Project page: http://shrimp7.googlecode.com/
* My blog: http://www.soepgarnaal.com/
* Twitter: http://twitter.com/soupshrimp
*
* Licensed under the BSD license.
*/

(function(window){
	// shrimp7 constructor function, inspired by jQuery (John Resig)
	var shrimp7 = function constructor(){
		return new shrimp7.fn.init();
	},
	// Window document in local var for better minification
	doc = window.document,
	activeDom = null,
	sidebar = "sidebar",
	web = "web",
	json = 'json',
	soepgarnaalURL = 'http://www.soepgarnaal.com/',
	config = {
		system: 'web'
	},
	language = {},
	systemGadget,
	// Auto check for sidebar, if sidebar is used inject System.Gadget object
	// in local var for better minification
	configFunc=(function(){
		if(config.system===sidebar){
			systemGadget = System.Gadget;
		}
	})(),
	/*
	* setting(settingName,[setValue],[callback])
	*/
	setting=function(){
		var returnValue="",c_start,c_end;
		if(arguments.length===1){
			if(config.system===sidebar){
				return systemGadget.Settings.read(arguments[0]);
			}
			else{
				if(doc.cookie.length>0){
					c_start = doc.cookie.indexOf(arguments[0] + "=");
					if(c_start!=-1){
						c_start=c_start+arguments[0].length+1;
						c_end=doc.cookie.indexOf(";",c_start);
						if(c_end==-1){
							c_end = doc.cookie.length;
						}
						returnValue = unescape(doc.cookie.substring(c_start,c_end));
						
						if(returnValue==='true'){
							returnValue = TRUE;
						}
						if(returnValue==='false'){
							returnValue = FALSE;
						}
					}
				}
			}
		}
		if(arguments.length===2){
			if(config.system===sidebar){
				systemGadget.Settings.write(arguments[0], arguments[1]);
			}else{
				var exdate = new Date(), expiredays = 10;
				exdate.setDate(exdate.getDate()+expiredays);
				doc.cookie = arguments[0] + "=" + escape(arguments[1]) + ((expiredays == NULL) ? "" : ";expires=" + exdate.toGMTString());
			}
		}
		if(arguments.length===3){
			arguments[2](returnValue);
			return window.shrimp7;
		}else{
			return returnValue;
		}
	},
	loading=function(section,state,type){
		if(type=='full'){
			state ? $("#"+section+"Loading").show() : $("#"+section+"Loading").hide();
		}else{
			if(state){
				if(!$("#loading").is(':visible')){
					$("#loadingBox").html('<span id="loading"><img id="loadingImg"src="images/icons/loading.gif"alt="Loading"/></span>');
				}
			}else{
				$("#loading").remove();
			}
		}
	},
	executeFunctionByName=function(functionName,context,args){
		var	namespaces = functionName.split("."),
			func = namespaces.pop(),
			i;
		for(i=0;i<namespaces.length;i++){
			context = context[namespaces[i]];
		}
		return context[func].call(this,args);
	},
	changeLanguage=function(toLang){
		$("#settingsLanguageSelector option[value='"+toLang+"']",activeDom).attr("selected","selected");
		
		language = window["shrimp7_language_"+toLang]();
		
		setting("language",toLang);
		
		$("*[class^=lngMain]",activeDom).each(function(){
			var classDef = $(this,activeDom).attr("class").replace('.','');
			if(this.tagName.toLowerCase()==='input'){
				$(this,activeDom).val(language[classDef]);
			}else{
				$(this,activeDom).html(language[classDef]);
			}
		});
	},
	setDimensions=function(w,h,useWidthRatio){
		if(config.system===sidebar){
			if(useWidthRatio==='width'){
				h = Math.round(w / 1.18);
			}else{
				if(useWidthRatio==='height'){
					w = Math.round(h * 1.18);
				}
			}
			
			$("body,#gadgetBackground",activeDom).width(w).height(h);
			$("#container",activeDom).width(w - 10).height(h - 20);
		}else{
			$("#flyout").dialog('option', 'height', h);
		}
	},
	randomString=function(){
		var chars = "ABCDEFGHJKLMNPQRSTWXTZacefghikmnopqrstwxyz", string_length = 8, randomstring = '', i, rnum;
		for(i=0;i<string_length;i++){
			rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum, rnum + 1);
		}
		return randomstring;
	},
	startTimer=function(section){
		switch(section){
			case 'facebook':
				shrimp7.facebook.timer = setTimeout(shrimp7.facebook.timerStarter,60000);
			break;
			case 'twitter':
				shrimp7.twitter.timer = setTimeout(function(){
					twitter.fetchTimeline(true);
				}, 3600000 / parseInt(setting("twitterRefreshTimeline"),10));
			break;
			case 'friendfeed':
				shrimp7.friendfeed.timer = setTimeout(friendfeedTimerStarter,60000);
			break;
		}
		return window.shrimp7;
	},
	stopTimer=function(section){
		switch(section){
			case 'facebook':
				clearTimeout(shrimp7.facebook.timer);
			break;
			case 'twitter':
				clearTimeout(shrimp7.twitter.timer);
			break;
			case 'friendfeed':
				clearTimeout(shrimp7.friendfeed.timer);
			break;
		}
		return window.shrimp7;
	},
	stateChecked = 0,
	checkStateCall=function(){
		if(stateChecked===0){
			if(config.system===sidebar){
				setting("size","");
				checkState('normal');
			}else{
				setting("size","_web");
				checkState('_web');
			}
		}else{
			setting("size","");
			checkState('normal');
		}
	},
	checkState=function(type){
	
	},
	paging=function(total,maxPerPage,startId){
		var endId, previousStart, nextStart, htmlStr = '';
		
		if(total>maxPerPage){
			if((startId+maxPerPage)<total){
				endId = startId + maxPerPage;
				previousStart = (startId - (maxPerPage));
				nextStart = endId;
			}else{
				previousStart = (startId - (maxPerPage));
				if((total-startId)>startId){
					nextStart = (total-startId);
				}else{
					nextStart = NULL;
				}
				endId = total;
			}
		}else{
			nextStart = NULL;
			endId = total;
		}
		
		return{
			"endId": endId,
			"previousStart": previousStart,
			"nextStart": nextStart
		};
	},
	parseLinks=function(str){
		return str.replace(/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1'>$1</a>") + '</span>';
	},
	emoticons=function(str){
		var front='<img src="images/emoticons/',back='.png"/>',
		replace=[/:\)/g,/:-\)/g,/:\(/g,/:-\(/g,/:d/ig,/:-d/ig,/:p/ig,/:-p/ig,/;\)/g,/:s/ig,'&lt;3','<3'],
		replaceWith=["smile","smile","sad","sad","grin","grin","tongue","tongue","wink","confused","love","love"],
		i;
		for(i=0;i<replace.length;i++){
			str = str.replace(replace[i],front+replaceWith[i]+back);
		}
		return str;
	},
	relativeTime = function(time_value, type){
		if(type==='timestamp'){
			var relative_to = new Date().getTime(),delta;
			
			relative_to = (relative_to / 1000);
			delta = relative_to - time_value;
		}
		
		if(delta<30){
			return language.lngMainTimesLessThen30SecondsAgo;
		}else if(delta<60){
			return language.lngMainTimesLessThenAminuteAgo;
		}else if(delta<120){
			return language.lngMainTimesAboutAminuteAgo;
		}else if(delta<2700){
			return (parseInt(delta / 60)).toString() + ' ' + language.lngMainTimesMinutesAgo;
		}else if(delta<5400){
			return language.lngMainTimesAboutAnHourAgo;
		}else if(delta<86400){
			return language.lngMainTimesAbout + ' ' + (parseInt(delta/3600)).toString() + ' ' + language.lngMainTimesHoursAgo;
		}else if(delta<172800){
			return language.lngMainTimesOneDayAgo;
		}else{
			return (parseInt(delta/86400)).toString() + ' ' + language.lngMainTimesDaysAgo;
		}
	},
	sortById=function(a,b){
		var x = a.id;
		var y = b.id;
		return ((x<y) ? +1 : ((x>y) ? -1 : 0));
	},
	// Some vars for extreme minification
	UNDEFINED = undefined,
	NULL = null,
	TRUE = true,
	FALSE = false,
	click = "click",
	errorTxt = "error",
	checked = "checked",
	htmlImgIconsFront = '<img src="images/icons/',
	twitterURL = 'http://twitter.com/';
	
	shrimp7.fn = shrimp7.prototype = {
		init:function(){
			if(setting("started")===""){
				setting("started", 0);
			}else{
				setting("started", parseInt(setting("started")) + 1);
			}
			
			$(function(){
				if(setting("language")!==""){
					changeLanguage(setting("language"));
				}else{
					changeLanguage('english');
				}
			});
			
			if(config.system===sidebar){
				systemGadget.onDock = checkStateCall; // This will be fired when the gadget is loaded.. and fired when docked after loading..
				systemGadget.onUndock = checkStateCall;
				systemGadget.visibilityChanged = checkVisibility;
			}else{
				checkStateCall();
			}
			
			return this;
		},
		toggleScreen:function(obj){
			var	init = function(){
					if(obj.init!==UNDEFINED){
						obj.init();
					}
				},
				close = function(){
					if(obj.close!==UNDEFINED){
						obj.close();
					}
				},
				temp,params;
			if(obj.type==='flyout'){
				$("#screenHeaderTitle").html(obj.title);
				
				if(obj.init!==UNDEFINED){
					executeFunctionByName(obj.init,window,NULL);
				}
				
				$("#screenClose").unbind(click).click(function(){
					if(obj.close!==UNDEFINED){
						executeFunctionByName(obj.close,window,NULL);
					}
					hideFlyout(obj);
				});
				
				$("#screen,#"+obj.id).show();
			}
			if(obj.type==='element'||obj.type==='dialog'){
				// get the screen html and put it in var temp
				temp = $("#"+obj.id).andSelf().show();
				// remove the original screen html from the document
				$("#"+obj.id).remove();
				// push the screen HTML in to the dropIn element
				$(obj.dropIn).html(temp);
			}
			if(obj.type==='element'){
				init();
				
				$("#screenHeaderTitle").html(obj.title);
				
				$("#screenClose").unbind(click).click(function(){
					close();
				});
				
				$("#screen,#"+obj.id).show();
			}
			if(obj.type==='dialog'){
				init();
				
				// create and open the dialog
				$(obj.dropIn).dialog({
					title:obj.title,
					open:function(){
						if(obj.onOpen!==UNDEFINED){
							obj.onOpen(obj.params);
						}
					},
					close:function(event,ui){
						close();
						
						$("#"+obj.id).remove();
						if(obj.screenParentId===UNDEFINED){
							$("#shrimp7screenContent").append(temp);
						}else{
							$(obj.screenParentId).append(temp);
						}
						
						// destroy the dialog
						$(obj.dropIn).dialog('destroy');
					}
				});
			}
			if(obj.returnSelf!==FALSE){
				return this;
			}
		},
		hideFlyout:function(obj){
			if(config.system===sidebar){
				System.Gadget.Flyout.show = FALSE;
			}else{
				if(config.iframe){
					$("#screen,#"+obj.id).hide();
					$("#content").show();
				}else{
					$("#flyout").dialog('close');
				}
			}
		}
	};
	
	shrimp7.fn.init.prototype = shrimp7.fn;
	
	shrimp7.main = shrimp7.fn.main = {
		
	};
	
	shrimp7.languageSet = shrimp7.fn.languageSet = {};
	// Make setting available for outside calls
	shrimp7.setting = shrimp7.fn.setting = setting;
	
	shrimp7.changeLanguage = shrimp7.fn.changeLanguage = changeLanguage;